// page/component/orders/orders.js
var request_api = require('../../../utils/require_api.js')
import Dialog from '../../../youzan/youzan_dist/dialog/dialog';
import Toast from '../../../youzan/youzan_dist/toast/toast';
const app = getApp();
Page({
  data: {
    address: {},
    hasAddress: false,
    total: 0,
    orders: [],
    some_orders: [], //获取到的该订单款信息
    goodsid: '',
    money: 0,
    sFiled: '',
    sColorid: '',
    sgoodsid: '',
    snum: '',
    ssizeclass: '',
    orderotem: [],
    jsonobj: '',
  },

  onLoad: function (options) {
    var that = this;
    that.data.sFiled = '';
    that.data.sColorid = '';
    that.data.sgoodsid = '';
    that.data.snum = '';
    that.data.ssizeclass = '';
    this.data.jsonobj = options.jsonobj;
    if (options.jsonobj != undefined) {
      var data = JSON.parse(options.jsonobj);
      console.log(data.color_show, "jsonobj");
      console.log(data, "console.log(data.color_show, ");
      request_api.request( //插入數據到r_order表  订单表 
        'getinstallgoumai', {
          goods: data.goods,
          filed: data.filed,
          size_class: data.size_class,
          color_show: data.color_show
        },
        function (res) {
          console.log(data.number_select, "我是陈国基");
          let some_order = res.data[0];
          that.data.sFiled = data.filed;
          that.data.sColorid = data.color_show;
          that.data.sgoodsid = data.goods;
          that.data.snum = data.number_select;
          that.data.ssizeclass = data.size_class;
          res.data[0].num = data.number_select;
          that.setData({
            orders: res.data
          })

          that.getTotalPrice(res.data);
        },
        function () {
          console.log("錯誤");
        },
      )
    } else {
      this.data.goodsid = options.order_item;

      //获取到订单的款信息 参数是对应的款id
      request_api.request(
        'getorders_item', {
          id: options.order_item
        },
        function (res) {
          that.data.some_orders = res.data;
          for (let i = 0; i < that.data.some_orders.length; i++) {
            if (that.data.some_orders[i].Filed != '' || that.data.some_orders[i].Filed != null) {
              that.data.sFiled = that.data.sFiled + that.data.some_orders[i].Filed + ',';
            }
            if (that.data.some_orders[i].colorId != '' || that.data.some_orders[i].colorId != null) {
              that.data.sColorid = that.data.sColorid + that.data.some_orders[i].colorId + ',';
            }
            if (that.data.some_orders[i].goods_id != '' || that.data.some_orders[i].goods_id != null) {
              that.data.sgoodsid = that.data.sgoodsid + that.data.some_orders[i].goods_id + ',';
            }
            if (that.data.some_orders[i].num != '' || that.data.some_orders[i].num != null) {
              that.data.snum = that.data.snum + that.data.some_orders[i].num + ',';
            }
            if (that.data.some_orders[i].size_class != '' || that.data.some_orders[i].size_class != null) {
              that.data.ssizeclass = that.data.ssizeclass + that.data.some_orders[i].size_class + ',';
            }
          }
          that.setData({
            orders: res.data
          })
          that.data.orderotem = res.data;
          that.getTotalPrice(that.data.some_orders); //计算总价
        },
        function () {
          console.log("錯誤");
        },
      )
    }
  },

  onShow: function () {
    const self = this;
    wx.getStorage({
      key: 'address',
      success(res) {
        self.setData({
          address: res.data,
          hasAddress: true
        })
      }
    })
  },

  /**
   * 计算总价
   */
  getTotalPrice(orders) {
    let total = 0;
    for (let i = 0; i < orders.length; i++) {
      total += orders[i].num * orders[i].price;
    }
    this.setData({
      total: this.numberFormat(total)
    })
  },

  numberFormat: function (value) {
    var v = parseFloat(value) //强转Int，毕竟有可能返回是String类型的数字
    return v.toFixed(2)
  },

  //获取微信的地址信息
  get_wcAddress() {
    wx.chooseAddress({
      success: (res) => {
        wx.setStorage({
          key: 'address',
          data: res,
          success() {
            console.log(res, "我是地址");
          }
        })
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },
  //点击提交订单触发事件里面首先判断有没有填写收货地址，然后判断余额是否够扣除，都
  //可以执行的时候就弹出对话框是否扣除金额，是的话生成订单状态为待发货，否的话也生成订单，
  //订单状态为未支付状态，为支付状态可以点击订单详情去支付，支付成功之后就是订单状态改为
  //待发货，待发货状态就是需要后台去处理发货，更改订单的状态为发货状态。发货状态之后就是
  //用户可以确认收货，和退货功能  update_del_user
  toorder() {
    var that = this;

    if (1 != 1) {

    } else {



      wx.getStorage({
        key: 'address',
        success(res) {
          var outTradeNo = ""; //订单号
          for (var i = 0; i < 3; i++) //6位随机数，用以加在时间戳后面。
          {
            outTradeNo += Math.floor(Math.random() * 10);
          }
          outTradeNo = new Date().getTime() + outTradeNo; //时间戳，用来生成订单号。
          //把地址存入到r_order_devi   物流表
          request_api.request( //插入到订单款到订单详细表
            'insertorder_delivery', {
              "orderid": outTradeNo,
              "provinceName": res.data.provinceName,
              "cityName": res.data.cityName,
              "countyName": res.data.countyName,
              "detailInfo": res.data.detailInfo,
              "userName": res.data.userName,
              "telNumber": res.data.telNumber,
              "nationalCode": res.data.nationalCode,
            }, //需要传的 data
            function (res) {
              // console.log(res, "我是插入到orderitem上的数据")
            }
          )
          //需要的操作：删除掉购物车表的款详情，插入order表和订单详情表
          request_api.request( //插入到订单款到订单详细表
            'insertgoodsitem', {
              "sFiled": that.data.sFiled,
              "sColorid": that.data.sColorid,
              "sgoodsid": that.data.sgoodsid,
              "snum": that.data.snum,
              "ssizeclass": that.data.ssizeclass,
              "order_id": outTradeNo
            }, //需要传的 data
            function (res) {
              // console.log(res, "我是插入到orderitem上的数据")
            }
          )
          //   openid   outTradeNo 订单号  that.data.money 总金额 
          request_api.request( //插入數據到r_order表  订单表 
            'insert_orders', {
              orderId: outTradeNo,
              userId: app.globalData.openid,
              totalmoney: that.data.total,
              orderstatus: 0
            },
            function (res) {
              console.log(res, "reas");
            },
            function () {
              console.log("錯誤");
            },
          )
          if (that.data.jsonobj != undefined) {

          } else {
            //删除对应商品的库存  
            let goods_ids = '';
            let num = '';
            let size_class = '';
            let Filed = '';
            let colorid = '';
            for (let i = 0; i < that.data.orderotem.length; i++) {
              goods_ids += that.data.orderotem[i].goods_id + ',';
              num += that.data.orderotem[i].num + ',';
              colorid += that.data.orderotem[i].colorId + ',';
              Filed += that.data.orderotem[i].Filed + ',';
              size_class += that.data.orderotem[i].size_class + ',';
            }
            request_api.request( //减少库存数量
              'update_f002qua', {
                quatity: num,
                goodsid: goods_ids,
                fileds: Filed,
                size_classs: size_class,
                colorid: colorid
              },
              function (res) {
                console.log(res, "我是减少的库存");
              },
              function () {
                console.log("錯誤");
              },
            )

            request_api.request( //删除购物车款 
              'delete_shopping_cart_bylist', {
                id: that.data.goodsid
              },
              function (res) {
                console.log(res, "我是删除掉购物车功能");
              },
              function () {
                console.log("錯誤");
              },
            )
          }

          //删除用户对应的购物车物品
          //生成订单号绑定用户的openid，总价，订单状态（未支付状态），创建时间，物流编号，生成订单详细表
          //把订单号和对应的款号尺码颜色数量单价总价图片地址
          Toast.loading({
            duration: 2000, // 持续展示 toast
            forbidClick: true, // 禁用背景点击
            message: '加载中......',
            loadingType: 'spinner',
          });
          setTimeout(function () {
            Toast.success('订单提交成功');
            wx.redirectTo({
              url: '../orderpage/orderpage?order_item=' + outTradeNo,
            })
          }, 2500);
        },
        fail: function (err) {
          Toast.fail('请填写地址！');
        }
      })
    }
  }
})